package com.ifish.leetcode.problem.algorithm;

import com.ifish.leetcode.problem.BaseLeetCodeProblem;

/**
 * Created by iFish on 2017/7/9.
 */

public class _0006 extends BaseLeetCodeProblem {
    @Override
    public String title() {
        return "ZigZag Conversion";
    }

    @Override
    public int difficulty() {
        return 1;
    }

    @Override
    public void run() {
        super.run();

        String result = convert("PAYPALISHIRING", 2);
        printResult(result);
    }

    public String convert(String s, int n) {
        if (n == 1 || s.length() == 1)
            return s;

        int round = 2 * (n - 1); // 一次曲折需要几个字符
        int len = s.length();
        // record current index of a row
        StringBuffer[] sb = new StringBuffer[n];
        for (int i = 0; i < n; i++) {
            sb[i] = new StringBuffer();
        }

        int roundPos = 0;
        for (int i = 0; i < len; i++) {
            int rowPos = roundPos <= n - 1 ? roundPos : round - roundPos; // V的 左侧 右侧
//            System.out.print(rowPos + " ");
            sb[rowPos].append(s.charAt(i)); // 把每个字符放到对应位置buffer的最后
            roundPos = roundPos + 1 >= round ? 0 : roundPos + 1; // reset round position
        }

        for (int i = 1; i < n; i++) {
            sb[0].append(sb[i]);
        }
        return sb[0].toString();
    }
}
